package org.dawnsql.stock.util;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

public class MyScript {

    private static String path = MyScript.class.getResource("").getPath();
    private static int index = path.lastIndexOf("/org/dawnsql/stock/util/");
    private static String line = path.substring(0, index) + "/static/";

    public static String getJs(String code)
    {
        // 初始化模板引擎
        VelocityEngine velocityEngine = new VelocityEngine();
        //velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        //velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.setProperty(velocityEngine.FILE_RESOURCE_LOADER_PATH, line);
        velocityEngine.init();

        // 获取模板文件
        Template template = velocityEngine.getTemplate("script.vm");

        // 设置变量，velocityContext是一个类似map的结构
        VelocityContext velocityContext = new VelocityContext();
//        velocityContext.put("name", "world");
//        List<String> list = new ArrayList<String>();
//        list.add("jack");
//        list.add("kitty");
//        velocityContext.put("list", list);

        // 输出渲染后的结果
        StringWriter stringWriter = new StringWriter();
        template.merge(velocityContext, stringWriter);
        //System.out.println(stringWriter.toString());
        return stringWriter.toString();
    }
}
